package com.cn.icss.interceptor;

import com.alibaba.fastjson.JSON;
import com.cn.icss.vo.common.ResponseCode;
import com.cn.icss.vo.common.ResponseResult;
import com.cn.icss.vo.common.ResponseStatus;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.ActionException;
import com.jfinal.core.Controller;
import org.apache.log4j.Logger;

import java.util.Arrays;


/**
 * @中软华腾软件系统有限公司,未经授权不得擅自传播
 * @类描述: 统一异常处理
 * @类名称:ExceptionHandler
 * @作者: Administrator
 * @编辑时间: 2020/04/08 16:26
 * @版本: 1.0
 */
public class ExceptionHandlerInterceptor implements Interceptor {

    Logger logger = Logger.getLogger(ExceptionHandlerInterceptor.class);

    @Override
    public void intercept(Invocation inv) {
        ResponseResult responseResult  =  null;
        Controller controller = null;
        try{
            controller = inv.getController();
            inv.invoke();
        }catch (ActionException e){
            logger.error(e.getMessage());
            responseResult = new ResponseResult(e.getErrorCode(),e.getMessage(),false, null);
            controller.renderJson(JSON.toJSONString(responseResult));
        } catch (Exception e){
            logger.error(e.getMessage());
            Arrays.stream(e.getStackTrace()).forEach(x->{
                logger.error(x);
            });
            responseResult = ResponseResult.build(ResponseCode.Error, e.getMessage(), ResponseStatus.FAIL);
            controller.renderJson(JSON.toJSONString(responseResult));
        }

    }
}
